package calao.util;

import java.util.Vector;

public class Arrays {

	public static boolean contains(int[] array, int value)
	{
		for (int aval : array) if (value==aval) return true;
		return false;
	}
		
	public static <T> boolean contains(T[] array, T value)
	{
		if (value==null) throw new NullPointerException();
		for (T aval : array) {
			if (aval!=null && aval.equals(value)) return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public static <T> T[] newArray(Class<T> type, int length)
	{
		return (T[])java.lang.reflect.Array.newInstance(type, length);
	}
	
	public static <T> T[] toArray(Vector<T> vector, Class<T> type)
	{
		return vector.toArray(newArray(type, vector.size()));
	}
	
	public static <T> T[] append(T[] array, T value)
	{
		T[] result = java.util.Arrays.copyOf(array, array.length+1);
		result[array.length] = value;
		return result;
	}
	
	/** Removes any occurence of a value in an array.
	 */
	public static <T> T[] remove(T[] array, T value)
	{
		int count = 0;
		for (T aval : array) if (!value.equals(aval)) count++;
		T[] result = java.util.Arrays.copyOf(array, count);
		int i = 0;
		for (T aval : array) if (!value.equals(aval)) result[i++] = aval;
		return result;
	}

	public static int[] append(int[] array, int value)
	{
		int[] result = java.util.Arrays.copyOf(array, array.length+1);
		result[array.length] = value;
		return result;
	}

	public static int[] cat(int[] array1, int[] array2)
	{
		int[] result = java.util.Arrays.copyOf(array1, array1.length+array2.length);
		System.arraycopy(array2, 0, result, array1.length, array2.length);
		return result;
	}

	public static int min(int[] array)
	{
		int result = Integer.MAX_VALUE;
		for (int value : array) if (value<result) result = value;
		return result;
	}

	public static int max(int[] array)
	{
		int result = Integer.MIN_VALUE;
		for (int value : array) if (value>result) result = value;
		return result;
	}

}
